package controllers

import (
	"encoding/json"
	"weiboxs.com/new_h_glasses/enums"
	"weiboxs.com/new_h_glasses/models"
)

type ProductsattributeController struct {
	BaseController
}

func (c *ProductsattributeController) Prepare() {
	//先执行
	c.BaseController.Prepare()
	c.Data["activeSidebarUrl"] = "/productsattribute/index"

}


func (c *ProductsattributeController) Index() {
	c.checkAuthor("productsattribute/index") //需要权限控制

	c.display("", "productsattribute/index_footerjs.html")
}

func (c *ProductsattributeController) DataGrid() {

	c.checkAuthor("productsattribute/index") //需要权限控制

	var params models.ErpProductsAttributeParam
	json.Unmarshal(c.Ctx.Input.RequestBody, &params)
	//获取数据列表和总数
	data := models.ErpProductsAttributeList(&params)

	c.jsonDataTable(0, data)
}

func (c *ProductsattributeController) Delete() {

	c.checkAuthor("productsattribute/index") //需要权限控制

	id, err := c.GetInt("id")
	if err != nil {
		c.jsonResult(enums.JRCodeFailed, "出错了", "")
	}

	m, err1 := models.ErpProductsAttributeGetById(id)
	if err1 != nil {
		c.jsonResult(enums.JRCodeFailed, err1.Error(), "")
	}

	if m.Status == 1 {
		m.Status = 0
	} else {
		m.Status = 1
	}

	if err := m.Update("status"); err != nil {
		c.jsonResult(enums.JRCodeFailed, err1.Error(), "")
	}
	c.jsonResult(enums.JRCodeSucc, "操作成功", "")
}

func (c *ProductsattributeController) Edit() {

	c.checkAuthor("productsattribute/index") //需要权限控制

	if c.Ctx.Request.Method == "POST" {
		c.Save()
	}
	Id, _ := c.GetInt(":id", 0)

	m := models.ErpProductsAttribute{Id: int64(Id)}
	if Id > 0 {
		gm, err := models.ErpProductsAttributeGetById(Id)
		if err != nil {
			c.pageError("数据无效，请刷新后重试")
		}
		c.Data["m"] = gm
	} else {
		c.Data["m"] = m
	}

	c.display("", "productsattribute/edit_footerjs.html", "shared/layout_dialog.html")
}

//Save 添加、编辑页面 保存
func (c *ProductsattributeController) Save() {
	var err error
	m := models.ErpProductsAttribute{}
	//获取form里的值
	if err = c.ParseForm(&m); err != nil {
		c.jsonResult(enums.JRCodeFailed, "获取数据失败", m.Id)
	}
	if m.Id == 0 {
		if _, err = models.ErpProductsAttributeAdd(&m); err == nil {
			c.jsonResult(enums.JRCodeSucc, "添加成功", m.Id)
		} else {
			c.jsonResult(enums.JRCodeFailed, "添加失败", m.Id)
		}

	} else {
		if err = m.Update("option_name", "typeid", "pinyin", "status", "OptionKey", "OptionContent"); err == nil {
			c.jsonResult(enums.JRCodeSucc, "编辑成功", m.Id)
		} else {
			c.jsonResult(enums.JRCodeFailed, "编辑失败", m.Id)
		}
	}
}

